<template>
  <div id="comment">
    <!-- 头部 title -->
    <div class="c-header">
      <em>{{ commentsCount }}&nbsp;</em>条评论
    </div>
    <!-- 主回复框 -->
    <comment-input
      :is-main="true"
      :avatar="userInfo.avatarUrl"
      :group_id="group_id"
      :item_id="item_id"></comment-input>
    <!-- 评论列表 -->
    <ul>
      <li class="c-item" v-for="(item, index) in options.list">
        <!-- 头像 -->
        <a :href="'/c/user/' + item.user.user_id + '/'" target="_blank" class="avatar-wrap">
          <img v-if="item.user.avatar_url" :src="item.user.avatar_url" alt="">
        </a>
        <div class="c-content">
          <!-- 名字+时间 -->
          <div class="c-user-info">
            <a :href="'/c/user/' + item.user.user_id + '/'" class="c-user-name" target="_blank">{{ item.user.name }}</a>
            <span class="c-create-time">{{ item.timeAgo }}</span>
          </div>
          <!-- 内容 -->
          <p>{{ item.text }}</p>
          <!-- 回复+展示回复+点赞+举报 -->
          <div class="c-footer-action">
            <span class="c-reply" @click="onReplyClick(item, index, true)" ga_event="click_reply_comment">回复</span>
            <span
              v-if="item.reply_count > 0 && !item.is_reply_expanded"
              class="c-reply-count"
              @click="getReplyComments(item, index)"
              ga_event="click_expand_reply"
            >&nbsp;&sdot;&nbsp;{{ item.reply_count }}条回复<tt-icon type="arrow_down" color="#406599" size="14"></tt-icon></span>
            <span
              v-if="item.is_reply_expanded"
              class="c-reply-count"
              @click="onReplyCollapseClick(item)"
            >&nbsp;&sdot;&nbsp;收起回复<tt-icon type="arrow_up" color="#406599" size="14"></tt-icon></span>
            <span class="bui-right c-report" @click="openReport(item)" title="举报">
              <tt-icon type="report" color="#cacaca" size="14"></tt-icon>
            </span>
            <span
              class="bui-right c-digg"
              :class="{'c-digg-active': item.user_digg}"
              @click="onDiggClick(item, true)"
              title="点赞"
              ga_event="click_good_comment">{{ item.diggNum }}&nbsp;<i class="bui-icon icon-thumbsup_line"></i></span>
          </div>
          <!-- 评论框占位 -->
          <div :class="'J_input_' + index"></div>
          <!-- 回复评论的评论列表 -->
          <div v-for="(subItem, subIndex) in item.reply_data.reply_list" class="c-reply-comment">
            <!-- 头像 -->
            <a :href="'/c/user/' + subItem.user.user_id + '/'" target="_blank" class="avatar-wrap">
              <img v-if="subItem.user.avatar_url" :src="subItem.user.avatar_url" alt="">
            </a>
            <div class="c-content">
              <!-- 名字+时间 -->
              <div class="c-user-info">
                <a :href="'/c/user/' + subItem.user.user_id + '/'" target="_blank" class="c-user-name">{{ subItem.user.name }}</a>
                <span class="c-create-time">{{ subItem.timeAgo }}</span>
              </div>
              <!-- 内容 -->
              <p>{{ subItem.text }}</p>
              <!-- 回复+点赞 -->
              <div class="c-footer-action">
                <span class="c-reply" @click="onReplyClick(subItem, subIndex, false)" ga_event="click_reply_comment">回复</span>
                <span
                  class="bui-right c-digg"
                  :class="{'c-digg-active': subItem.user_digg}"
                  @click="onDiggClick(subItem, false)"
                  title="点赞"
                  ga_event="click_good_comment">{{ subItem.diggNum }}&nbsp;<i class="bui-icon icon-thumbsup_line"></i></span>
              </div>
              <!-- 评论框占位 -->
              <div :class="'J_input_' + index + '_' + subIndex"></div>
            </div>
          </div>
          <!-- 加载更多回复评论的回复 -->
          <a v-if="item.reply_data.hasMore" class="c-load-more r-load-more" @click.prevent="getReplyComments(item, index)" ga_event="click_loadmore_reply">查看更多回复</a>
        </div>
      </li>
    </ul>
    <!-- 加载更多按钮 -->
    <a v-if="options.hasMore" class="c-load-more" @click.prevent="getComments" ga_event="click_loadmore_comment">查看更多评论</a>
    <a v-if="options.noMore && comments_count > 0" class="no-more-tips" href="//app.toutiao.com/news_article/" target="_blank">以上为热门评论，头条 App 还有更多内容</a>
    <!-- 反馈容器 -->
    <comment-input
      ref="childComment"
      :is-show-comment-box="commentBoxOptions.isShow"
      :group_id="group_id"
      :item_id="item_id"
      :dongtai_id="commentBoxOptions.dongtai_id"
      :pIndex="commentBoxOptions.pIndex"
      :subIndex="commentBoxOptions.subIndex"
      :sourceName="commentBoxOptions.sourceName"
      :sourceText="commentBoxOptions.sourceText"></comment-input>
    <comment-report
      v-on:closeReport="closeReport"
      :is-show-report="isShowReport"
      :reportData="reportData"
    ></comment-report>
  </div>
</template>
<style lang="less" rel="stylesheet/less">
  @import "./comment.less";
</style>
<script>
  import reqwest from 'reqwest'
  import Vue from 'vue'

  import CommentInput from './comment-input.vue'
  import CommentReport from './comment-report.vue'

  import eventBus from '../../../src/js/eventBus.js'
  import { timeAgo, numFormat } from '../../../src/js/utils.js'
  import checkLogin from '../../../src/js/user'
  import Cookies from 'js-cookie'

  export default {
    name: 'Comment',
    props: {
      group_id: {
        type: String,
        default: ''
      },
      item_id: {
        type: String,
        default: ''
      },
      comment_load_count: {
        type: Number,
        default: 5
      },
      ban_comment: {
        type: Number,
        default: 0
      },
      comments_count: {
        type: Number,
        default: 0
      },
      userInfo: {
        type: Object
      }
    },
    data() {
      return {
        commentBoxOptions: {
          isShow: false,
          dongtai_id: 0,
          pIndex: -1,
          subIndex: -1,
          sourceName: '',
          sourceText: ''
        },
        isShowReport: false,
        reportData: {},
        options: {
          list: [],
          hasMore: false,
          isLoading: false,
          noMore: false
        },
        params: {
          group_id: this.group_id,
          item_id: this.item_id,
          offset: 0,
          count: this.comment_load_count
        }
      }
    },
    computed: {
      commentsCount: function () {
        if (Object.prototype.toString.call(this.comments_count) !== '[object Number]') return false

        return this.comments_count.toString().split("").reverse().join("").replace(/(\d{3})(?=[^$])/g, "$1,").split("").reverse().join("")
      }
    },
    methods: {
      /**
       * 评论列表数据接口
       */
      getComments (type) {

        if (this.options.isLoading) {
          return false
        }

        this.options.isLoading = true

        reqwest({
          url: '/api/comment/list/',
          data: this.params,
          method: 'GET',
          success: (rs) => {
            if (rs.message === 'success') {
              this.options.hasMore = rs.data.has_more
              rs.data.comments = this.dataPreHandle(rs.data.comments)
              this.options.list = this.options.list.concat(rs.data.comments)
              this.params.offset += this.params.count
              this.options.isLoading = false
            }
            if (type === 'first') {
              this.params.count = 10
              // eventBus.$emit('commentReady')
            } else {
              if (this.options.hasMore) {
                this.options.hasMore = false
                this.options.noMore = true
              }
            }
          }
        })
      },
      /**
       * 评论的评论列表数据接口
       */
      getReplyComments (replyItem, parent) {

        // what???
        if (replyItem.reply_data.offset === undefined) {
          replyItem.reply_data.offset = 0
        }

        reqwest({
          url: '/api/comment/get_reply/',
          data: {
            comment_id: replyItem.id,
            dongtai_id: replyItem.dongtai_id,
            offset: replyItem.reply_data.offset,
            count: 20
          },
          method: 'GET',
          success: (rs) => {
            if (rs.message === 'success') {
              replyItem.is_reply_expanded = true
              replyItem.reply_data.hasMore = !!rs.data.has_more
              replyItem.reply_data.offset += 20
              this.setReplyParent(rs.data.data, parent)

              // 清空热门原有的几条评论
              if (replyItem.reply_data.offset === 0) {
                replyItem.reply_data.reply_list = []
              }

              replyItem.reply_data.reply_list = replyItem.reply_data.reply_list.concat(rs.data.data)
            }
          }
        })
      },
      /**
       * 评论列表数据预处理，处理相对时间和点赞数量文案
       */
      dataPreHandle (list) {

        list.forEach((ele, i) => {
          ele.timeAgo = timeAgo(ele.create_time)
          ele.diggNum = numFormat(ele.digg_count, 1)
          this.setReplyParent(ele.reply_data.reply_list, i)
        })

        return list
      },
      /**
       * 评论的评论处理相对时间和点赞数量文案，绑定父级评论对象信息
       */
      setReplyParent (replyList, parent) {
        replyList.forEach((ele) => {
          ele.parent = parent
          ele.timeAgo = timeAgo(ele.create_time)
          ele.diggNum = numFormat(ele.digg_count, 1)
        })
      },
      // 评论的评论收起
      onReplyCollapseClick (item) {
        item.is_reply_expanded = false
        item.reply_data.offset = 0
        item.reply_data.hasMore = false
        item.reply_data.reply_list = []
      },
      // 回复
      onReplyClick (item, index, isParent) {

        var activeClass = 'J_input_'

        if (isParent) {
          activeClass = activeClass + index
          this.commentBoxOptions.pIndex = index
          this.commentBoxOptions.subIndex = -1
        } else {
          activeClass = activeClass + item.parent + '_' + index
          this.commentBoxOptions.pIndex = item.parent
          this.commentBoxOptions.subIndex = index
        }

        this.commentBoxOptions.sourceName = item.user.name
        this.commentBoxOptions.sourceText = item.text
        this.commentBoxOptions.dongtai_id = item.dongtai_id
        this.commentBoxOptions.isShow = true

        // 主回复框缩回去
        eventBus.$emit('mainCommentInputBlur');

        var commentReq = () => {
          var nodes = document.getElementsByClassName(activeClass)
          nodes[0].appendChild(this.$refs.childComment.$el)
        }

        checkLogin({
          successCb: function () {
            commentReq()
          }
        })
      },
      // 举报
      closeReport () {
        this.isShowReport = false
      },
      openReport (item) {
        this.reportData = {
          user_id: item.user.user_id,
          comment_id: item.id,
          group_id: this.group_id,
          item_id: this.item_id
        }
        this.isShowReport = true
      },
      // 点赞
      onDiggClick (item, isParent) {

        var comment_id = item.id
        var dongtai_id = item.dongtai_id
        var diggUrl = '/api/comment/reply_digg/'

        if (isParent) {
          diggUrl = '/api/comment/digg/'
        }

        if (item.user_digg) return false

        var param = {
          comment_id: comment_id,
          dongtai_id: dongtai_id,
          group_id: this.group_id,
          item_id: this.item_id,
          action: 'digg'
        }

        var diggReq = () => {
          reqwest({
            url: diggUrl,
            headers: {
              'X-CSRFToken': Cookies.get('csrftoken')
            },
            data: param,
            method: 'POST',
            success: (rs) => {
              if (rs.message === 'success') {
                item.user_digg = 1
                item.digg_count += 1
                item.diggNum = numFormat(item.digg_count, 1)
              }
            }
          })
        }

        checkLogin({
          successCb: function() {
            diggReq()
          }
        })
      }
    },
    mounted() {

      // 首刷
      if (this.ban_comment === 0) {
        this.getComments('first')
      }

      /**
       * 监听 comment-input 内部 emit 的事件，来插入新回复的评论到指定位置
       */
      eventBus.$on('commentInsert', (data) => {

        // 数据操作
        var comment = {
          text: data.text,
          id: data.id,
          dongtai_id: data.dongtai_id,
          user: {
            avatar_url: this.userInfo.avatarUrl,
            user_id: this.userInfo.id,
            name: this.userInfo.name
          },
          reply_data: {
            reply_list: []
          },
          digg_count: 0,
          reply_count: 0,
          user_digg: 0,
          timeAgo: timeAgo(Math.floor(new Date().getTime() / 1000)),
          diggNum: numFormat(0, 1),
          parent: data.pIndex
        }

        // 如果是主列表则直接 unshift，如果是子评论则需要循环找到哪条的哪个位置插入
        if (data.isMain) {
          this.options.list.unshift(comment)
        } else {
          for (let i = 0, len = this.options.list.length; i < len; i++) {
            if (i === data.pIndex) {
              this.options.list[i].reply_data.reply_list.splice(data.subIndex + 1, 0, comment)
              break
            }
          }
          // 完毕，关上回复输入框
          eventBus.$emit('removeChildComment')
        }
      })
    },
    components: {
      CommentInput,
      CommentReport
    }
  }
</script>



// WEBPACK FOOTER //
// comment.vue?35252828
